package com.flipdf2;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.File;

import com.flipdf2.render.Render;
import com.flipdf2.render.RenderException;
import com.flipdf2.render.RenderedPage;

public class PDFStamp implements Stamp {
	private File pdfFile;
	private int pageNo;
	private Rectangle rect;

	private Image image;

	public PDFStamp(File pdfFile, int pageNo) {
		this.pdfFile = pdfFile;
		this.pageNo = pageNo;
		renderPage(this.pageNo);
	}

	public TYPE getType() {
		return TYPE.pdf;
	}

	public boolean containPoint(Point p) {
		return false;
	}

	public void draw(Graphics2D g) {
		Color oldColor = g.getColor();
		g.setColor(Color.RED);
		g.drawRect(0, 0, this.rect.width + 1, this.rect.height + 1);
		g.setColor(oldColor);
		g.drawImage(this.image, 1, 1, null);
	}

	public Rectangle getRect() {
		return this.rect;
	}

	public void setRect(Rectangle rect) {
		this.rect = rect;
	}

	public int getLayer() {
		return 0;
	}

	public void setPage(File pdfFile, int pageNo) {
		if (this.pdfFile.equals(pdfFile)) {
			if (this.pageNo == pageNo) {
				return;
			} else {
				this.pageNo = pageNo;
				renderPage(pageNo);
			}
		} else {
			this.pdfFile = pdfFile;
			this.pageNo = pageNo;
			renderPage(pageNo);
		}
	}

	private boolean renderPage(int pageNo) {
		try {
			Render render = Render.createRender(Render.SUN_PDF);
			render.openFile(pdfFile);
			RenderedPage page = render.getPage(pageNo);
			this.rect = page.getBBox().getBounds();
			Dimension pageSize = new Dimension((int) (page.getBBox().getWidth()), (int) (page
					.getBBox().getHeight()));
			this.image = page.getImage(pageSize.width, pageSize.height, page.getBBox(), null);
			return true;
		} catch (RenderException e) {
			e.printStackTrace();
		}
		return false;
	}
}
